import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.jibble.simpleftp.SimpleFTP;

public class FTPConnectivity {
	
	ConnectionStatus ftpStatus = new ConnectionStatus();	
	FTPClient client = null;
	FileOutputStream fos = null;
	FileInputStream fis = null;
	SimpleFTP ftp = null;	
	
	private String ftpUpload() {
		String uploadSpeed;
		double totalDuration = 0;
		double counter = 0; 
		double start;
		double end;
		String nameLocal = "chunk";
		
		boolean flag = false;
		int badAttempts = 0;
		
		File f = new File(nameLocal);
		System.out.println("File exists? " + f.exists());		
		
		try {
			ftp = new SimpleFTP();
			ftp.connect("ftp.drivehq.com", 21, "mifcais", "COMSE6181");
			ftp.bin();
			System.out.println(ftp.cwd("/AIS"));
			System.out.println(ftp.pwd());
			
			while (totalDuration < 20000) {
				if (badAttempts >= 4)
					break;			
				try {				
					counter++;
					System.out.println("Upload #" + counter);					
					start = System.currentTimeMillis();
					ftp.stor(f);
					end = System.currentTimeMillis();
					totalDuration += (end-start);							
				} catch (Exception e) {
					flag = true;
					badAttempts++;
					System.out.println("Something went wrong while uploading (pt.1)");
				} finally {
					try {
						if (fis != null) {
							fis.close();
						}			
					} catch (Exception e) {
						flag = true;
						badAttempts++;
						System.out.println("Something went wrong while uploading (pt.2)");
					}
				}
			} // end while
			ftp.disconnect();
		} catch (Exception e) {
			System.out.println("Cannot connect in upload");
		}
		
		// delete local file so as to leave the state as in the beginning of the execution.
		// Note that for this to work we have to call ftpDownload first! 
		File flocal = new File(nameLocal);		
		if(flocal.exists()) {
			System.out.println("Did we manage to delete local file? " + flocal.delete());
		}		
		
		if ( (flag == true) && (counter == 1) )
			uploadSpeed = "???";
		else
			uploadSpeed = Double.toString((1024.0*counter)/(totalDuration/1000.0));
		
		return uploadSpeed;
	}

	private String ftpDownload() {		
		String downloadSpeed;
		double totalDuration = 0;
		int counter = 0; 
		double start;
		double end;
		String nameLocal = "chunk";
		String nameRemote = "chunk";
		boolean retrieve;
		boolean flag = false;
		int badAttempts = 0;
		
		try {
			client = new FTPClient();
			client.connect("ftp.drivehq.com",21);
			client.login("mifcais","COMSE6181");
			client.cwd("/AIS/");	
			
			while (totalDuration <= 20000) {
				try {
					if (badAttempts >= 4)
						break;	
					counter++;
					System.out.println("Download #" + counter);			
					File flocal = new File(nameLocal);
					if(flocal.exists()) {
						System.out.println("Did we manage to delete local file? " + flocal.delete());
					}
					else
						System.out.println("Local file did not exist");
					fos = new FileOutputStream(nameLocal);			

					System.out.println("We are connected");
					FTPFile[] files = client.listFiles();
					for (int i = 0; i < files.length; i++) {
						System.out.println("#" + i + " :   " + files[i]);
					}							
					start = System.currentTimeMillis();
					retrieve = client.retrieveFile(nameRemote, fos);
					end = System.currentTimeMillis();
					System.out.println("Time for this dl: " + (end-start) + " ms");
					totalDuration += (end-start);
					System.out.println("Did we manage to retrieve the file from ftp? " + retrieve);
				} catch (Exception e) {
					flag = true;
					badAttempts++;
					System.out.println("Something went wrong while downloading (pt.1)");
				} finally {
					try {
						if (fos != null) {
							fos.close();
						}
					} catch (IOException e) {
						flag = true;
						badAttempts++;
						System.out.println("Something went wrong while downloading (pt.2");
					}
				}
			} // end of while
			
			client.disconnect();
			
		} catch (Exception e) {
			System.out.println("Cannot Connect");
		}		
		
		if ( (flag == true) && (counter == 1) )
			downloadSpeed = "???";
		else
			downloadSpeed = Double.toString((1024.0*counter)/(totalDuration/1000.0));
		
		return downloadSpeed;
	}
	
	// attempts to connect n times and reports the result (green/yellow/red)
	public ConnectionStatus runTests()  {
		ftpStatus.currentLightStatus = ConnectionStatus.lights.RED;
		ftpStatus.downloadSpeed = ftpDownload();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			;
		}
		ftpStatus.uploadSpeed = ftpUpload();
		
		return ftpStatus;
	}

}
 